/*
 * 文件名：Encrypt.java
 * 版权：Copyright 2006-2011 AsiaInfo Tech. Co. Ltd. All Rights Reserved. 
 * 描述： Encrypt.java
 * 修改人：Administrator
 * 修改时间：2011-8-24
 * 修改内容：新增
 */
package com.fengxing.ams.pub.util;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import com.fengxing.ams.pub.UtilityException;

/**
 * token鉴权
 * 
 * @author ebusu
 * @version CTMS V100R001 2011-8-24
 * @since CTMS V100R001C01
 */
public class AESUtil
{
    /**
     * 
     * 加密
     * 
     * @param keyStr
     *            密钥
     * @param content
     *            需要加密的内容
     * @return byte[]
     */
    public static byte[] aesEncode(String keyStr, String content)
    {
        try
        {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");

            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(keyStr.getBytes("UTF-8"));
            kgen.init(128, secureRandom);

            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            byte[] byteContent = content.getBytes("UTF-8");
            cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
            byte[] result = cipher.doFinal(byteContent);
            return result;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            // 密钥错误
            throw new UtilityException(e);
        }
    }

    /**
     * 
     * 解密
     * 
     * @param keyStr
     *            密钥
     * @param content
     *            需要解密的内容
     * @return byte[]
     */
    public static byte[] aesDecode(String keyStr, byte[] content)
    {
        try
        {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");

            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(keyStr.getBytes("UTF-8"));
            kgen.init(128, secureRandom);

            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
            byte[] result = cipher.doFinal(content);
            return result; // 加密
        }
        catch (Exception e)
        {
            e.printStackTrace();
            // 密钥错误
            throw new UtilityException(e);
        }
    }
}
